package com.hopu.oa.controller.UserManage;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.hopu.oa.dao.UserManage.UserManageDao;
import com.hopu.oa.entity.dto.user.manage.UserManage;
import com.hopu.oa.entity.user.AoaPosition;
import com.hopu.oa.entity.user.AoaUser;
import com.hopu.oa.service.UserManageService.UserManageService;
import com.hopu.oa.until.MD5Util;
import com.hopu.oa.until.data.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.unit.DataUnit;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class UserManageController {


    @Autowired
    private UserManageService userManageService;


    @Autowired
    private UserManageDao userManageDao;

    @RequestMapping("/usermanage")
    public String manage_index(
            @RequestParam(value = "page", defaultValue = "1") int page, @RequestParam(value = "size", defaultValue = "8") int size,
            String find,
            HttpSession session, Model model) {
        System.out.println("find = " + find);
        // 获取当前用户
        AoaUser user = (AoaUser) session.getAttribute("user");

        //获取符合条件总条数
        int totalElements = userManageService.queryStaffCount(user.getRoleId(), user.getDeptId(), find);

        //页数
        int totalPages = totalElements % size == 0 ? totalElements / size : totalElements / size + 1;

        // 获取符合条件部门员工
        List<UserManage> users =
                userManageService.queryStaffByUserRoleOrDept(user.getRoleId(), user.getDeptId(), (page - 1) * size, size, find);

        System.out.println(users);

        HashMap<String, Integer> map1 = new HashMap<>();
        map1.put("totalElements", totalElements);
        map1.put("totalPages", totalPages);
        map1.put("number", page);
        map1.put("size", size);
        model.addAttribute("url", "usermanagepaging");

        //push
        model.addAttribute("page", map1);
        model.addAttribute("find", find);
        model.addAttribute("users", users);
        return "user/usermanage";
    }


    @RequestMapping("usermanagepaging")
    public String manage_index2(
            @RequestParam(value = "page", defaultValue = "1") int page,
            @RequestParam(value = "size", defaultValue = "8") int size,
            String find,
            HttpSession session, Model model) {

        // 获取当前用户
        AoaUser user = (AoaUser) session.getAttribute("user");

        //获取符合条件总条数
        int totalElements = userManageService.queryStaffCount(user.getRoleId(), user.getDeptId(), find);
        ;

        //页数
        int totalPages = totalElements % size == 0 ? totalElements / size : totalElements / size + 1;


        // 获取符合条件部门员工
        List<UserManage> users =
                userManageService.queryStaffByUserRoleOrDept(user.getRoleId(), user.getDeptId(), (page - 1) * size, size, find);

        System.out.println(users);

        HashMap<String, Integer> map1 = new HashMap<>();
        map1.put("totalElements", totalElements);
        map1.put("totalPages", totalPages);
        map1.put("number", page);
        map1.put("size", size);
        model.addAttribute("url", "usermanagepaging");

        //push
        model.addAttribute("page", map1);
        model.addAttribute("find", find);
        model.addAttribute("users", users);
        return "user/usermanagepaging";
    }


    /*
      @Description : 删除用户
      @Date   :  2021/11/15
      @Param  : [userId]
      @return : java.lang.Boolean
     */
    @RequestMapping("userManage_deleteUser/{userId}")
    @ResponseBody
    public Boolean deleteUser(@PathVariable int userId) {
        return userManageService.userManage_deleteUserById(userId);
    }


    @RequestMapping("useredit")
    public String useredit(Model model, HttpSession session, String userid, Integer page) {

        /*
           修改用户
          2021/11/16
          [model, session, userid]
          java.lang.String
         */
        AoaUser thisUser = (AoaUser) session.getAttribute("user");

        //修改用户
        if (userid != null) {

            AoaUser user = userManageService.queryUpdateUserById(userid);
            //查询部门编号，部门名字
            List<Map<String, String>> depts = userManageService.queryDeptIdAndDeptName(thisUser.getRoleId(), thisUser.getDeptId());
            //查询role,查自己能给的
            List<Map<String, String>> roles = userManageService.queryRoleByUserId(thisUser.getRoleId());

        /*
          数据封装model
         */
            model.addAttribute("depts", depts);
            model.addAttribute("roles", roles);
            model.addAttribute("user", user);
            model.addAttribute("page", page);
            System.out.println(user);
            return "user/edituser";

        } else {
            /*
            新增用户
            */
            //查询部门编号，部门名字
            List<Map<String, String>> depts = userManageService.queryDeptIdAndDeptName(thisUser.getRoleId(), thisUser.getDeptId());

            //查询role,查自己能给的
            AoaUser user = (AoaUser) session.getAttribute("user");
            List<Map<String, String>> roles = userManageService.queryRoleByUserId(user.getRoleId());

            System.out.println(roles);


        /*
          数据封装model
         */
            model.addAttribute("depts", depts);
            model.addAttribute("roles", roles);
            //model.addAttribute("user",user);
            return "user/edituserInsetr";

        }


    }


    /*
      @Description :  部门联动职位
      @Date   :  2021/11/15
      @Param  : [id]
      @return : java.util.List<com.hopu.oa.entity.user.AoaPosition>
     */
    @RequestMapping("queryPositionIdAndName")
    @ResponseBody
    public List<AoaPosition> queryPositionIdAndName(int id) {
        //查询职位编号，职位名字
        List<AoaPosition> positions = userManageService.queryPositionIdAndPositionName(id);
        return positions;
    }


    /*
      @Description : 修改，添加用户
      @Date   :  2021/11/16
      @Param  : [user, session]
      @return : java.lang.String
     */
    @RequestMapping("manage_useradd")
    public String manage_useradd(UserManage user, HttpSession session, Integer page) throws Exception {

        System.out.println("==============================================================");
        System.out.println(user);

        System.out.println("page = " + page);


        System.out.println(user);


        //当前用户
        AoaUser aoaUser = (AoaUser) session.getAttribute("user");

        if (user.getUserId() != null && (!user.getUserId().equals(""))) {
            Integer manageUserId = new Integer(user.getUserId());
            if (!(manageUserId.intValue() == aoaUser.getUserId().intValue())) {
                // 修改
                userManageService.updateUserByUser(user);
            }

        } else {


            String birth = getBirthday(user.getUserIdcard());
            user.setBirth(birth);

            int fatherId = userManageDao.queryFatherId(user.getDeptId());
            user.setFatherId(fatherId + "");

            user.setImgPath("https://2oa-file.oss-cn-beijing.aliyuncs.com/t/2021-11-30/83e1c0930f3748a39292c33bb2acd74c-lbw.jpg");
            user.setIsLock(0);
            String str = "123456";
            String md5Encode = MD5Util.md5Encode(str);
            //初始默认密码加密后存入库
            user.setPassword(md5Encode);
            user.setHireTime(DateUtils.getDateTimeString());
            user.setSuperman("0");

            userManageService.insertUser(user);
        }
        System.out.println(user);


        return "redirect:/usermanage?page=" + page;


    }


    /**
     * 15位身份证号
     */
    private static final Integer FIFTEEN_ID_CARD = 15;
    /**
     * 18位身份证号
     */
    private static final Integer EIGHTEEN_ID_CARD = 18;
    private static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");


    /**
     * 获取出生日期  yyyy年MM月dd日
     *
     * @param IDCard
     * @return
     */
    public static String getBirthday(String IDCard) {


        String birthday = "";
        String year = "";
        String month = "";
        String day = "";
        if (StringUtils.isNotBlank(IDCard)) {
            //15位身份证号
            if (IDCard.length() == FIFTEEN_ID_CARD) {
                // 身份证上的年份(15位身份证为1980年前的)
                year = "19" + IDCard.substring(6, 8);
                //身份证上的月份
                month = IDCard.substring(8, 10);
                //身份证上的日期
                day = IDCard.substring(10, 12);
                //18位身份证号
            } else if (IDCard.length() == EIGHTEEN_ID_CARD) {
                // 身份证上的年份
                year = IDCard.substring(6).substring(0, 4);
                // 身份证上的月份
                month = IDCard.substring(10).substring(0, 2);
                //身份证上的日期
                day = IDCard.substring(12).substring(0, 2);
            }
            birthday = year + "-" + month + "-" + day + "-";
        }
        return birthday;
    }

}
